﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Security.Cryptography;

namespace Project
{
    public partial class Anketa : Form
    {
        DataTable dtPhone = new DataTable();
        DataTable dtAddress = new DataTable();
        DataTable dtReferees = new DataTable();
        DataTable dtSecondDocument = new DataTable();
        string path = @"C:\Users\Ольга\Desktop\";
        byte[] desKey = new byte[] { 1, 2, 4, 5, 6, 7, 8, 9 };
        byte[] desIV = new byte[] { 1, 2, 4, 5, 6, 7, 8, 9 };

        public Anketa()
        {
            InitializeComponent();
            #region таблица телефонов
            dtPhone.Columns.Add(new DataColumn("id_typePhone", typeof(int)));
            dtPhone.Columns.Add(new DataColumn("TypePhone",typeof(string)));
            dtPhone.Columns.Add(new DataColumn("phoneNumber", typeof(long)));
            dtPhone.Columns.Add(new DataColumn("Mask", typeof(string)));
            #endregion

            #region таблица адресов
            dtAddress.Columns.Add(new DataColumn("ID_AddressType", typeof(int)));
            dtAddress.Columns.Add(new DataColumn("AddressType", typeof(string)));
            dtAddress.Columns.Add(new DataColumn("AddressIndex",typeof(string)));
            dtAddress.Columns.Add(new DataColumn("Area", typeof(string)));
            dtAddress.Columns.Add(new DataColumn("Rayon", typeof(string)));
            dtAddress.Columns.Add(new DataColumn("City", typeof(string)));
            dtAddress.Columns.Add(new DataColumn("Street", typeof(string)));

            dtAddress.Columns.Add(new DataColumn("ID_HouseType", typeof(int)));
            dtAddress.Columns.Add(new DataColumn("HouseType", typeof(string)));
            dtAddress.Columns.Add(new DataColumn("HouseNumber", typeof(string)));

            dtAddress.Columns.Add(new DataColumn("ID_KorpusType", typeof(int)));
            dtAddress.Columns.Add(new DataColumn("KorpusType", typeof(string)));
            dtAddress.Columns.Add(new DataColumn("Korpus", typeof(string)));
            
            dtAddress.Columns.Add(new DataColumn("ID_FlatType", typeof(int)));
            dtAddress.Columns.Add(new DataColumn("FlatType", typeof(string)));
            dtAddress.Columns.Add(new DataColumn("Flat", typeof(string)));
            #endregion
            
            #region таблица рекомендателей
            dtReferees.Columns.Add(new DataColumn("Surname",typeof(string)));
            dtReferees.Columns.Add(new DataColumn("Name", typeof(string)));
            dtReferees.Columns.Add(new DataColumn("Patroname", typeof(string)));
            dtReferees.Columns.Add(new DataColumn("ID_ParentRelation", typeof(int)));
            dtReferees.Columns.Add(new DataColumn("ParentRelation",typeof(string)));
            dtReferees.Columns.Add(new DataColumn("ID_typePhone", typeof(int)));
            dtReferees.Columns.Add(new DataColumn("typePhone", typeof(string)));
            dtReferees.Columns.Add(new DataColumn("phoneNumber", typeof(long)));
            dtReferees.Columns.Add(new DataColumn("Mask", typeof(string)));
            dtReferees.Columns.Add(new DataColumn("IsClosePeople", typeof(int)));
            dtReferees.Columns.Add(new DataColumn("ClosePeople", typeof(string)));
            #endregion

            #region таблица вторых документов
            dtSecondDocument.Columns.Add(new DataColumn("ID_TypeSecondDocument",typeof(int)));
            dtSecondDocument.Columns.Add(new DataColumn("TypeSecondDoc", typeof(string)));
            dtSecondDocument.Columns.Add(new DataColumn("Number",typeof(string)));           
            #endregion
        }
        
        private void bSaveCustomer_Click(object sender, EventArgs e)
        {
            string Surname = tbSurname.Text;
            string Name = tbName.Text;
            string Patroname = tbPatroname.Text;
            string sFileName = path+"ExampleXML.xml";
                        
            /*//Создаем пустой XML - документ:
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(sFileName);
                //а это - корень дерева
                XmlNode root = doc.LastChild;
                root.AppendChild(createnode(doc));

                //сохранение
                System.IO.FileStream fs = new System.IO.FileStream(sFileName, System.IO.FileMode.OpenOrCreate);
                //doc.InnerXml();
                doc.Save(fs);
                fs.Flush();
                fs.Close();
            }
            catch (Exception ex)
            {                
                XmlNode root;
                root = doc.CreateNode(XmlNodeType.Element, "root", "");
                //мы создали элемент... а теперь мы его добавим к дереву.
                doc.AppendChild(root);

                //oNode.InnerText = ;// + "; " + fio + "; " + dSum.ToString() + "; " + dtValue.ToShortDateString();
                root.AppendChild(createnode(doc));
                //сохранение
                System.IO.FileStream fs = new System.IO.FileStream(sFileName, System.IO.FileMode.OpenOrCreate);
                //doc.InnerXml();
                doc.Save(fs);
                fs.Flush();
                fs.Close();
            }*/

            convertAndSave();
            this.Close();
        }

        public XmlAttribute createatribute(XmlDocument doc, string name, string value)
        {
            XmlAttribute newnode = doc.CreateAttribute("n", name, "");
            newnode.Value = value;
            return newnode;
        }
        public XmlNode createnode(XmlDocument doc)
        {
            XmlNode oNode = null;
            oNode = doc.CreateNode(XmlNodeType.Element, "Person", "");

            XmlNode chilPerson = doc.CreateNode(XmlNodeType.Element, "First", "");
            oNode.AppendChild(chilPerson);
            chilPerson.Attributes.Append(createatribute(doc, "Surname", tbSurname.Text));
            chilPerson.Attributes.Append(createatribute(doc, "Name", tbName.Text));
            chilPerson.Attributes.Append(createatribute(doc, "Patroname", tbPatroname.Text));

            #region пол
            int id_gender=-1;
            if (rbMen.Checked)
                id_gender = 1;
            if (rbWomen.Checked)
                id_gender=2;

            chilPerson.Attributes.Append(createatribute(doc, "ID_Gender", id_gender.ToString()));
            #endregion

            chilPerson.Attributes.Append(createatribute(doc, "BirthdayDate", tbBirthday.Text));
            chilPerson.Attributes.Append(createatribute(doc, "BirthdayRegion", tbBirthdayRegion.Text));
            chilPerson.Attributes.Append(createatribute(doc, "BirthdayRayon", tbBirthdayRayon.Text));
            chilPerson.Attributes.Append(createatribute(doc, "BirthdayCity", tbBirthdayCity.Text));
            chilPerson.Attributes.Append(createatribute(doc, "BirtdayPlace", tbBirthdayPlace.Text));

            #region семейное положение
            int id_MaritalStatus = -1;
            if (rbMaritalStatusGB.Checked)
                id_MaritalStatus = 5;
            if (rbMaritalStatusBrack.Checked)
                id_MaritalStatus = 6;
            if (rbMaritalStatusNoBrak.Checked)
                id_MaritalStatus = 7;

            chilPerson.Attributes.Append(createatribute(doc, "ID_MaritalStatus", id_MaritalStatus.ToString()));
            #endregion

            #region образование
            int id_education = -1;
            if (rbEducationV.Checked)
                id_education = 1;
            if (rbEducationNoV.Checked)
                id_education = 2;
            if (rbEducationSS.Checked)
                id_education = 3;
            if (rbEducationS.Checked)
                id_education = 4;

            chilPerson.Attributes.Append(createatribute(doc, "ID_Education", id_education.ToString()));
            #endregion

            #region документы
            chilPerson.Attributes.Append(createatribute(doc, "PassportNum", tbPassportNum.Text.Replace(" ", string.Empty)));
            chilPerson.Attributes.Append(createatribute(doc, "PassportPlace", tbPassportPlace.Text));
            chilPerson.Attributes.Append(createatribute(doc, "PassportDate", tbPassportDate.Text));

            
            for (int i = 0; i < dtSecondDocument.Rows.Count; i++)
            {
                XmlNode child = doc.CreateNode(XmlNodeType.Element, "SecondDoc", "");
                oNode.AppendChild(child);
                child.Attributes.Append(createatribute(doc, "ID_TypeSecondDoc", dtSecondDocument.Rows[i]["ID_TypeSecondDocument"].ToString()));
                child.Attributes.Append(createatribute(doc, "Number", dtSecondDocument.Rows[i]["Number"].ToString()));
            }
            #endregion

            #region телефоны
            for (int i = 0; i < dtPhone.Rows.Count; i++)
                {
                    XmlNode child = doc.CreateNode(XmlNodeType.Element, "Phone", "");
                    oNode.AppendChild(child);
                    child.Attributes.Append(createatribute(doc, "TypePhone", dtPhone.Rows[i]["typePhone"].ToString()));
                    child.Attributes.Append(createatribute(doc, "PhoneNumber", dtPhone.Rows[i]["phoneNumber"].ToString()));
                    child.Attributes.Append(createatribute(doc, "Mask", dtPhone.Rows[i]["Mask"].ToString()));
                }
            #endregion

            #region адреса
            for (int i = 0; i < dtAddress.Rows.Count; i++)
                {
                    XmlNode child = doc.CreateNode(XmlNodeType.Element, "Address", "");
                    oNode.AppendChild(child);
                    child.Attributes.Append(createatribute(doc, "ID_AddressType", dtAddress.Rows[i]["AddressType"].ToString()));
                    child.Attributes.Append(createatribute(doc, "AddressIndex", dtAddress.Rows[i]["AddressIndex"].ToString()));
                    child.Attributes.Append(createatribute(doc, "Area", dtAddress.Rows[i]["Area"].ToString()));
                    child.Attributes.Append(createatribute(doc, "Rayon", dtAddress.Rows[i]["Rayon"].ToString()));
                    child.Attributes.Append(createatribute(doc, "City", dtAddress.Rows[i]["City"].ToString()));
                    child.Attributes.Append(createatribute(doc, "Street", dtAddress.Rows[i]["Street"].ToString()));
                    child.Attributes.Append(createatribute(doc, "ID_AddressType", dtAddress.Rows[i]["AddressType"].ToString()));
                    child.Attributes.Append(createatribute(doc, "HouseNumber", dtAddress.Rows[i]["HouseNumber"].ToString()));
                    child.Attributes.Append(createatribute(doc, "HouseType", dtAddress.Rows[i]["HouseType"].ToString()));
                    child.Attributes.Append(createatribute(doc, "Korpus", dtAddress.Rows[i]["Korpus"].ToString()));
                    child.Attributes.Append(createatribute(doc, "KorpusType", dtAddress.Rows[i]["KorpusType"].ToString()));
                    child.Attributes.Append(createatribute(doc, "Flat", dtAddress.Rows[i]["Flat"].ToString()));
                    child.Attributes.Append(createatribute(doc, "FlatType", dtAddress.Rows[i]["FlatType"].ToString()));
                }
                #endregion

            #region рекомендатели
            for (int i = 0; i < dtReferees.Rows.Count; i++)
            {
                XmlNode child = doc.CreateNode(XmlNodeType.Element, "Referess", "");
                oNode.AppendChild(child);
                child.Attributes.Append(createatribute(doc, "Surname", dtReferees.Rows[i]["Surname"].ToString()));
                child.Attributes.Append(createatribute(doc, "Name", dtReferees.Rows[i]["Name"].ToString()));
                child.Attributes.Append(createatribute(doc, "Patroname", dtReferees.Rows[i]["Patroname"].ToString()));
                child.Attributes.Append(createatribute(doc, "ClosePeople", dtReferees.Rows[i]["ClosePeople"].ToString()));
                child.Attributes.Append(createatribute(doc, "ParentRelation", dtReferees.Rows[i]["ParentRelation"].ToString()));
                child.Attributes.Append(createatribute(doc, "typePhone", dtReferees.Rows[i]["typePhone"].ToString()));
                child.Attributes.Append(createatribute(doc, "phoneNumber", dtReferees.Rows[i]["phoneNumber"].ToString()));
                child.Attributes.Append(createatribute(doc, "Mask", dtReferees.Rows[i]["Mask"].ToString()));
            }
            #endregion

            #region работа
            //РУКОВОДИТЕЛЬ
            XmlNode chil = doc.CreateNode(XmlNodeType.Element, "RukWork", "");
            oNode.AppendChild(chil);
            chil.Attributes.Append(createatribute(doc, "Surname", tbSurnameRuk.Text));
            chil.Attributes.Append(createatribute(doc, "Name", tbNameRuk.Text));
            chil.Attributes.Append(createatribute(doc, "Patroname", tbPatronameRuk.Text));

            int typePhoneRuk =0; 
            if (cbPhoneType.SelectedIndex==0)
                typePhoneRuk = 2;
            if (cbPhoneType.SelectedIndex == 1)
                typePhoneRuk = 1;
            if (cbPhoneType.SelectedIndex == 2)
                typePhoneRuk = 3;

            chil.Attributes.Append(createatribute(doc, "TypePhone", typePhoneRuk.ToString()));

            string mask = "";
            long number = 0;
            GetPhone(tbPhoneRuk.Text, ref mask, ref number);
            chil.Attributes.Append(createatribute(doc, "Phone", number.ToString()));
            chil.Attributes.Append(createatribute(doc, "Mask", mask));

            //специалист ОК
            XmlNode chilKadr = doc.CreateNode(XmlNodeType.Element, "KadrWork", "");
            oNode.AppendChild(chilKadr);
            chilKadr.Attributes.Append(createatribute(doc, "Surname", tbSurnameK.Text));
            chilKadr.Attributes.Append(createatribute(doc, "Name", tbNameK.Text));
            chilKadr.Attributes.Append(createatribute(doc, "Patroname", tbPatronameK.Text));

            int typePhoneKadr = 0;
            if (cbPhoneType.SelectedIndex == 0)
                typePhoneKadr = 2;
            if (cbPhoneType.SelectedIndex == 1)
                typePhoneKadr = 1;
            if (cbPhoneType.SelectedIndex == 2)
                typePhoneKadr = 3;

            chilKadr.Attributes.Append(createatribute(doc, "TypePhone", typePhoneKadr.ToString()));
                        
            GetPhone(tbPhoneRuk.Text, ref mask, ref number);
            chilKadr.Attributes.Append(createatribute(doc, "Phone", number.ToString()));
            chilKadr.Attributes.Append(createatribute(doc, "Mask", mask));
            #endregion  

            #region прочее

            XmlNode newChild = doc.CreateNode(XmlNodeType.Element, "Other", "");
            oNode.AppendChild(newChild);
            newChild.Attributes.Append(createatribute(doc, "WorkName", tbNameWork.Text));
            newChild.Attributes.Append(createatribute(doc, "WorkSphere", tbWorkSphere.Text));
            newChild.Attributes.Append(createatribute(doc, "WorkPost", tbPost.Text));
            //адрес места работы
            newChild.Attributes.Append(createatribute(doc, "WorkArea", tbWorkArea.Text));
            newChild.Attributes.Append(createatribute(doc, "WorkCity", tbWorkCity.Text));
            newChild.Attributes.Append(createatribute(doc, "WorkStreet", tbWorkStreet.Text));
            newChild.Attributes.Append(createatribute(doc, "WorkHouseNumber", tbWorkHouseNumber.Text));
            //адрес сайта, где найдено место работы
            newChild.Attributes.Append(createatribute(doc, "WorkCiteAddress", tbSiteAddress.Text));
            //адрес отсутствует в силу специфики деятельности
            newChild.Attributes.Append(createatribute(doc, "WorkNoAddress", (chbNoAddress.Checked) ? "1" : "0"));

            int stag = 0;
            if (tbStagY.Text.Length > 0)
                stag = Convert.ToInt32(tbStagY.Text);
            stag += Convert.ToInt32(tbStagM.Text);
            newChild.Attributes.Append(createatribute(doc, "WorkStag", stag.ToString()));

            newChild.Attributes.Append(createatribute(doc, "AvgIncome", tbAvgIncom.Text));
            newChild.Attributes.Append(createatribute(doc, "AvgOut", tbAvgOut.Text));
            newChild.Attributes.Append(createatribute(doc, "DopIncome", tbDopIncom.Text));
            newChild.Attributes.Append(createatribute(doc, "PrepaymentDay", tbPrepaymentDate.Text));
            newChild.Attributes.Append(createatribute(doc, "SalaryDay", tbSallaryDay.Text));

            newChild.Attributes.Append(createatribute(doc, "HasDependens", ((rbDependY.Checked) ? 1 : 0).ToString()));
            newChild.Attributes.Append(createatribute(doc, "Dependents", tbDependCount.Text));

            newChild.Attributes.Append(createatribute(doc,"HasAvto",((rbAvtoY.Checked)?1:0).ToString()));
            newChild.Attributes.Append(createatribute(doc,"AvtoMark",tbAvtoMark.Text));
            newChild.Attributes.Append(createatribute(doc,"AvtoModel",tbAvtoModel.Text));
            newChild.Attributes.Append(createatribute(doc,"AvtoNumber",tbAvtoNumber.Text));
            newChild.Attributes.Append(createatribute(doc,"AvtoYear",tbAvtoYear.Text));
            newChild.Attributes.Append(createatribute(doc,"AvtoProperty",tbAvtoPersent.Text));

            newChild.Attributes.Append(createatribute(doc,"HasHome",((rbHouseY.Checked)?1:0).ToString()));
            newChild.Attributes.Append(createatribute(doc,"HomeRegion",tbHouseArea.Text));
            newChild.Attributes.Append(createatribute(doc,"HomeRayon",tbHouseRayon.Text));
            newChild.Attributes.Append(createatribute(doc,"HomeCity",tbHouseCity.Text));
            newChild.Attributes.Append(createatribute(doc,"HomeStreet",tbHouseStreet.Text));
            newChild.Attributes.Append(createatribute(doc,"HomeHouseNumber",tbHouseNumber.Text));
            newChild.Attributes.Append(createatribute(doc,"HomeHouseKorpus",tbHouseKorpus.Text));
            newChild.Attributes.Append(createatribute(doc,"HomeHouseFlat",tbHouseFlat.Text));
            newChild.Attributes.Append(createatribute(doc,"HomeProperty",tbHousePersent.Text));

            newChild.Attributes.Append(createatribute(doc,"Crime",((rbCrimeY.Checked)?1:0).ToString()));
            newChild.Attributes.Append(createatribute(doc,"crimeArticle","Статья "+tbCrimeArticle.Text+": "+tbCrime.Text ));
            #endregion
            return oNode;

        }

        //добавление данных в таблицы формы
        #region Phone
        private void bAddPhone_Click(object sender, EventArgs e)
        {
            DataRow row =dtPhone.NewRow();
            if (rbCellPhone.Checked)
            {
                row["id_typePhone"] = 2;
                row["TypePhone"] = rbCellPhone.Text;
            }
            if (rbHomePhone.Checked)
            {                
                row["id_typePhone"] = 1;
                row["TypePhone"] = rbHomePhone.Text;
            }
            if (rbWorkPhone.Checked)
            {
                row["id_typePhone"] = 3;
                row["TypePhone"] = rbWorkPhone.Text;
            }
            
            string mask="";
            long number=0;
            GetPhone(tbNumber.Text,ref mask,ref number);
            row["phoneNumber"] = number;
            row["Mask"] = mask;
            dtPhone.Rows.Add(row);
            dgPhone.DataSource = dtPhone;
            dgPhone.Columns[0].Visible = false;
            dgPhone.Columns[1].HeaderText = "Тип телефона";
            dgPhone.Columns[2].HeaderText = "Номер телефона";
            dgPhone.Columns[3].Visible = false;
        }

        //разбиваем введенный телефон на номер и маску
        public static void GetPhone(string sPhone, ref string Mask, ref long Phone)
        {
            StringBuilder sbMask = new StringBuilder();
            StringBuilder sbPhone = new StringBuilder();
            foreach (char ch in sPhone)
            {
                if (char.IsDigit(ch))
                {
                    sbPhone.Append(ch);
                    sbMask.Append('0');
                }
                else
                    sbMask.Append(ch);
            }
            Mask = sbMask.ToString();
            long lValue = -1;
            if (long.TryParse(sbPhone.ToString(), out lValue))
                Phone = lValue;
            else
                Phone = -1;
        }

        private void bModyfyPhone_Click(object sender, EventArgs e)
        {
            bDeleteSecondDoc_Click(null, null);
            bAddPhone_Click(null, null);
        }

        private void bDeletePhone_Click(object sender, EventArgs e)
        {
            dgPhone.Rows.RemoveAt(dgSecondDoc.SelectedCells[0].RowIndex);
        }

        private void dgPhone_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            int prCurrentRow = e.RowIndex;
            dgPhone.Rows[prCurrentRow].Selected = true;
        }

        private void dgPhone_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1) return;
            int prCurrentRow = e.RowIndex;
            dgPhone.Rows[prCurrentRow].Selected = true;
            DataGridViewSelectedCellCollection dgvcell = dgPhone.SelectedCells;
            var dgvc = dgvcell[0];
            var dgvr = dgvc.OwningRow;

            int typePhone = int.Parse(dgvr.Cells[0].Value.ToString());

            if (typePhone == 2)
                rbCellPhone.Checked = true;
            if (typePhone == 1)
                rbHomePhone.Checked = true;
            if (typePhone == 3)
                rbWorkPhone.Checked = true;

            tbPhone.Text = dgvr.Cells[2].Value.ToString();

        }
        #endregion

        #region Address
        private void bAddAddress_Click(object sender, EventArgs e)
        {
            DataRow row = dtAddress.NewRow();
            if (rbAddressRegistration.Checked)
            {
                List<int> typeAddress = new List<int>();
                for (int i=0;i<dgAddress.Rows.Count-1;i++)
                {
                     typeAddress.Add(int.Parse(dgAddress[0, i].Value.ToString()));
                }
                typeAddress.Sort();
                if (typeAddress.Count != 0)
                {
                    if (typeAddress[0] == 1)
                    {
                        MessageBox.Show("Адрес регистрации существует!");
                        return;
                    }
                }
                row["ID_AddressType"] = 1;
                row["AddressType"] = rbAddressRegistration.Text;
                
            }
            if (rbAddressResidential.Checked)
            {
                    row["ID_AddressType"] = 2;
                    row["AddressType"] = rbAddressResidential.Text;
            }
                
            
            
            row["AddressIndex"] = tbAddressIndex.Text;
            row["Area"] = tbArea.Text;
            row["Rayon"] = tbRayon.Text;
            row["City"] = tbCity.Text;
            row["Street"] = tbStreet.Text;
            row["HouseNumber"] = tbHouse.Text;
            if ((cbHouseType.SelectedIndex != -1) && (cbHouseType.SelectedIndex == 1))
            {
                row["ID_HouseType"] = 1;
                row["HouseType"] = cbHouseType.Items[1].ToString();
            }
            else
            {
                row["ID_HouseType"] = 0;
                row["HouseType"] = cbHouseType.Items[0].ToString();
            }
                
            
            row["Korpus"] = tbKorpus.Text;
            if ((cbKorpusType.SelectedIndex != -1)&&(cbKorpusType.SelectedIndex == 1))
            {
                row["ID_KorpusType"] = 1;
                row["KorpusType"] = cbKorpusType.Items[1];
            }
            else
            {
                row["ID_KorpusType"] = 0;
                row["KorpusType"] = cbKorpusType.Items[0];
            }            
            row["Flat"] = tbFlat.Text;
            if ((cbFlatType.SelectedIndex != -1)&&(cbFlatType.SelectedIndex == 0))
            {
                row["ID_FlatType"] = 1;
                row["FlatType"] = cbFlatType.Items[1];
            }
            else
            {
                row["ID_FlatType"] = 0;
                row["FlatType"] = cbFlatType.Items[0];
            }
            dtAddress.Rows.Add(row);
            dgAddress.DataSource = dtAddress;
            dgAddress.Columns[0].Visible = false;
            dgAddress.Columns[1].HeaderText = "Тип адреса";
            dgAddress.Columns[2].HeaderText = "Индекс";
            dgAddress.Columns[3].HeaderText = "Область";
            dgAddress.Columns[4].HeaderText = "Район";
            dgAddress.Columns[5].HeaderText = "Город";
            dgAddress.Columns[6].HeaderText = "Улица";
            dgAddress.Columns[7].Visible = false;
            dgAddress.Columns[8].HeaderText = "";
            dgAddress.Columns[9].HeaderText = "Дом";
            dgAddress.Columns[10].Visible = false;
            dgAddress.Columns[11].HeaderText = "";
            dgAddress.Columns[12].HeaderText = "Корпус";
            dgAddress.Columns[13].Visible = false;
            dgAddress.Columns[14].HeaderText = "";
            dgAddress.Columns[15].HeaderText = "Квартира";
        }

        private void dgAddress_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            int prCurrentRow = e.RowIndex;
            dgAddress.Rows[prCurrentRow].Selected = true;
        }

        private void bModyfyAddress_Click(object sender, EventArgs e)
        {
            bDeleteAddress_Click(null, null);
            bAddAddress_Click(null, null);
        }

        private void dgAddress_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1) return;
            int prCurrentRow = e.RowIndex;
            dgAddress.Rows[prCurrentRow].Selected = true;
            DataGridViewSelectedCellCollection dgvcell = dgAddress.SelectedCells;
            var dgvc = dgvcell[0];
            var dgvr = dgvc.OwningRow;

            int typeAddress = int.Parse(dgvr.Cells[0].Value.ToString());
            if (typeAddress == 1)
                rbAddressRegistration.Checked = true;
            else
                rbAddressResidential.Checked = true;

            tbAddressIndex.Text = dgvr.Cells[2].Value.ToString();
            tbArea.Text = dgvr.Cells[3].Value.ToString();
            tbRayon.Text = dgvr.Cells[4].Value.ToString();
            tbCity.Text = dgvr.Cells[5].Value.ToString();
            tbStreet.Text = dgvr.Cells[6].Value.ToString();

            cbHouseType.SelectedIndex = int.Parse(dgvr.Cells[7].Value.ToString()) - 1;
            tbHouse.Text = dgvr.Cells[9].Value.ToString();

            cbKorpusType.SelectedIndex = int.Parse(dgvr.Cells[10].Value.ToString())-1;
            tbKorpus.Text = dgvr.Cells[12].Value.ToString();

            cbFlatType.SelectedIndex = int.Parse(dgvr.Cells[13].Value.ToString())-1;
            tbFlat.Text = dgvr.Cells[15].Value.ToString();
        }

        private void bDeleteAddress_Click(object sender, EventArgs e)
        {
            dgAddress.Rows.RemoveAt(dgAddress.SelectedCells[0].RowIndex);
        }
        #endregion

        #region Referees
        private void bAddReferees_Click(object sender, EventArgs e)
        {
            DataRow row = dtReferees.NewRow();

            row["Surname"]=tbSurnameReferees.Text;
            row["Name"]=tbNameReferees.Text;
            row["Patroname"]=tbPatronameReferees.Text;
            if (checkClosePeople.Checked)
            {
                row["IsClosePeople"] = 1;
                row["ClosePeople"] = "Близкий человек";
            }
            else
            {
                row["IsClosePeople"] = 0;
                row["ClosePeople"] = "";
            }
            row["ID_ParentRelation"]=cbParentRelation.SelectedIndex+1;
            row["ParentRelation"] = cbParentRelation.SelectedItem.ToString();
            if (cbPhoneType.SelectedIndex==0)
                row["ID_typePhone"] = 2;
            if (cbPhoneType.SelectedIndex == 1)
                row["ID_typePhone"] = 1;
            if (cbPhoneType.SelectedIndex == 2)
                row["ID_typePhone"] = 3;
            row["typePhone"] = cbPhoneType.SelectedItem.ToString();
            string mask = "";
            long number = 0;
            GetPhone(tbPhone.Text, ref mask, ref number);
            row["phoneNumber"] = number;
            row["Mask"] = mask;
            
            dtReferees.Rows.Add(row);
            dgReferees.DataSource = dtReferees;
            dgReferees.Columns[0].HeaderText = "Фамилия";
            dgReferees.Columns[1].HeaderText = "Имя";
            dgReferees.Columns[2].HeaderText = "Отчество";
            dgReferees.Columns[3].Visible = false;
            dgReferees.Columns[4].HeaderText = "Отношение к заемщику";
            dgReferees.Columns[5].Visible = false;
            dgReferees.Columns[6].HeaderText = "Тип телефона";
            dgReferees.Columns[7].HeaderText = "Номер телефона";
            dgReferees.Columns[8].Visible = false;
            dgReferees.Columns[9].Visible = false;
            dgReferees.Columns[10].HeaderText = "";
        }
        private void dgReferees_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            int prCurrentRow = e.RowIndex;
            dgReferees.Rows[prCurrentRow].Selected = true;
        }

        private void dgReferees_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1) return;
            int prCurrentRow = e.RowIndex;
            dgReferees.Rows[prCurrentRow].Selected = true;
            DataGridViewSelectedCellCollection dgvcell = dgReferees.SelectedCells;
            var dgvc = dgvcell[0];
            var dgvr = dgvc.OwningRow;

            tbSurnameReferees.Text = dgvr.Cells[0].Value.ToString();
            tbNameReferees.Text = dgvr.Cells[1].Value.ToString();
            tbPatronameReferees.Text = dgvr.Cells[2].Value.ToString();
            cbParentRelation.SelectedIndex = int.Parse(dgvr.Cells[3].Value.ToString()) - 1;
            cbPhoneType.SelectedIndex = int.Parse(dgvr.Cells[5].Value.ToString());
            tbPhone.Text = dgvr.Cells[7].Value.ToString();
            checkClosePeople.Checked = (1.Equals(int.Parse(dgvr.Cells[9].Value.ToString())));
        }

        private void bDeleteReferees_Click(object sender, EventArgs e)
        {
            dgReferees.Rows.RemoveAt(dgReferees.SelectedCells[0].RowIndex);
        }

        private void bModyfyReferees_Click(object sender, EventArgs e)
        {
            bDeleteReferees_Click(null, null);
            bAddReferees_Click(null, null);
        }
#endregion

        #region SecondDocument
        private void bADDSecondDoc_Click(object sender, EventArgs e)
        {
            DataRow row = dtSecondDocument.NewRow();

            #region тип второго документа
            int typeDoc= -1;
            typeDoc = cbSecondDoc.SelectedIndex + 1;
            //if (cbSecondDoc.SelectedIndex==0)
            //    typeDoc=1;
            //if (cbSecondDoc.SelectedIndex == 1)
            //    typeDoc = 2;
            //if (cbSecondDoc.SelectedIndex == 2)
            //    typeDoc = 3;
            //if (cbSecondDoc.SelectedIndex == 3)
            //    typeDoc = 4;
            //if (cbSecondDoc.SelectedIndex == 4)
            //    typeDoc = 5;
            //if (cbSecondDoc.SelectedIndex == 5)
            //    typeDoc = 6;
            //if (cbSecondDoc.SelectedIndex == 6)
            //    typeDoc = 7;
            row["ID_TypeSecondDocument"] = typeDoc;
            #endregion  

            row["TypeSecondDoc"] = cbSecondDoc.SelectedItem.ToString();
            row["Number"] = tbNumberSecondDoc.Text;
            dtSecondDocument.Rows.Add(row);
            dgSecondDoc.DataSource = dtSecondDocument;
            dgSecondDoc.Columns[0].Visible = false;
            dgSecondDoc.Columns[1].HeaderText = "Тип документа";
            dgSecondDoc.Columns[2].HeaderText = "Номер документа";
        }

        private void bModifySecondDoc_Click(object sender, EventArgs e)
        {
            bDeleteSecondDoc_Click(null, null);
            bADDSecondDoc_Click(null, null);
        }

        private void dgSecondDoc_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1) return;
            int prCurrentRow = e.RowIndex;
            dgSecondDoc.Rows[prCurrentRow].Selected = true;
            DataGridViewSelectedCellCollection dgvcell = dgSecondDoc.SelectedCells;
            var dgvc = dgvcell[0];
            var dgvr = dgvc.OwningRow;
            int selectvalue = int.Parse(dgvr.Cells[0].Value.ToString());

            cbSecondDoc.SelectedIndex = selectvalue - 1;
            tbNumberSecondDoc.Text = dgvr.Cells[2].Value.ToString();
        }

        private void bDeleteSecondDoc_Click(object sender, EventArgs e)
        {
            dgSecondDoc.Rows.RemoveAt(dgSecondDoc.SelectedCells[0].RowIndex);
        }
#endregion

        private void button1_Click_1(object sender, EventArgs e)
        {
            //ServiceReference.WebServiceSoapClient client = new ServiceReference.WebServiceSoapClient();

            //string s = File.ReadAllText(path+"ExampleXML.xml");

            //XmlDocument doc = new XmlDocument();
            //doc.LoadXml(s);
            //foreach (XmlNode xm in doc.ChildNodes)
            //{
            //    if (client.writeCustomerToBase(xm.InnerXml))
            //    {
            //        xm.ParentNode.RemoveChild(xm);
            //    }
            //    else
            //        MessageBox.Show("Не удалось сохранить!");
            //}
            
            EncryptData(path + "ExampleXML.xml", path + "out.txt", desKey, desIV);
            DescryptData(path + "out.txt", path + "out1.txt", desKey, desIV);
        }

        //блокирование полей для ввода
        private void selectDependents(object sender, EventArgs e)
        {
            if (rbDependY.Checked)
                tbDependCount.Enabled = true;
            if (rbDependN.Checked)
                tbDependCount.Enabled = false;
        }

        private void selectCrime(object sender, EventArgs e)
        {
            if (rbCrimeY.Checked)
            {
                tbCrime.Enabled = true;
                tbCrimeArticle.Enabled = true;
            }
            if (rbCrimeNo.Checked)
            {
                tbCrime.Enabled = false;
                tbCrimeArticle.Enabled = false;
            }
        }

        private void selectAvto(object sender, EventArgs e)
        {
            if (rbAvtoY.Checked)
            {
                tbAvtoMark.Enabled = true;
                tbAvtoModel.Enabled = true;
                tbAvtoNumber.Enabled = true;
                tbAvtoPersent.Enabled = true;
                tbAvtoYear.Enabled = true;
            }
            if (rbAvtoNo.Checked)
            {
                tbAvtoMark.Enabled = false ;
                tbAvtoModel.Enabled = false ;
                tbAvtoNumber.Enabled = false ;
                tbAvtoPersent.Enabled = false ;
                tbAvtoYear.Enabled = false ;
            }
        }

        private void selectHome(object sender, EventArgs e)
        {
            if (rbHouseY.Checked)
            {
                tbHousePersent.Enabled = true;
                tbHouseNumber.Enabled = true;
                tbHouseKorpus.Enabled = true;
                tbHouseFlat.Enabled = true;
                tbHouseCity.Enabled = true;
                tbHouseArea.Enabled = true;
                tbHouseRayon.Enabled = true;
                tbHouseStreet.Enabled = true;
            }
            if (rbHouseN.Checked)
            {
                tbHousePersent.Enabled = false ;
                tbHouseNumber.Enabled = false;
                tbHouseKorpus.Enabled = false;
                tbHouseFlat.Enabled = false;
                tbHouseCity.Enabled = false;
                tbHouseArea.Enabled = false;
                tbHouseRayon.Enabled = false;
                tbHouseStreet.Enabled = false;
            }
        }

        //смена масок вторых документов
        private void cbSecondDoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            int typeDoc = cbSecondDoc.SelectedIndex;
            switch (typeDoc)
            {
                case 0: 
                    tbNumberSecondDoc.Mask  = "0000000000000";
                    break;
                case 1:
                    tbNumberSecondDoc.Mask= "00 aa 000000";
                    break;
                case 2:
                    tbNumberSecondDoc.Mask = "";
                    break;
                case 3:
                    tbNumberSecondDoc.Mask = "";
                    break;
                case 4:
                    tbNumberSecondDoc.Mask = "000000";
                    break;
                case 5:
                    tbNumberSecondDoc.Mask = "000-000-000 00";
                    break;
                default:
                    tbNumberSecondDoc.Mask ="000000000000";
                    break;
            }
        }

        private void convertAndSave()
        {
            MemoryStream mem=new MemoryStream();
            FileStream fin = new FileStream(path+"out.txt", FileMode.Open, FileAccess.Read);
            //Create variables to help with read and write.
            byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
            long rdlen = 0;              //This is the total number of bytes written.
            long totlen = fin.Length;    //This is the total length of the input file.
            int len;                     //This is the number of bytes to be written at a time.

            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(mem, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
            //Read from the input file, then encrypt and write to the output file.
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
             
            }
            mem.Position=0;
            XmlDocument doc = new XmlDocument();
            doc.Load(mem);
            XmlNode root = doc.LastChild;
            root.AppendChild(createnode(doc));
            doc.Save(mem);
            
            EncryptData(mem, path + "out.txt", desKey, desIV);
        }

        private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
        {    
            //Create the file streams to handle the input and output files.
            FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            //Create variables to help with read and write.
            byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
            long rdlen = 0;              //This is the total number of bytes written.
            long totlen = fin.Length;    //This is the total length of the input file.
            int len;                     //This is the number of bytes to be written at a time.

            DES des = new DESCryptoServiceProvider();          
            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
            
            Console.WriteLine("Encrypting...");

            //Read from the input file, then encrypt and write to the output file.
            while(rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
                Console.WriteLine("{0} bytes processed", rdlen);
            }

            encStream.Close();  
            fout.Close();
            fin.Close();                   
         }

        private static void DescryptData(String inName, String outName, byte[] desKey, byte[] desIV)
        {
            //Create the file streams to handle the input and output files.
            FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            //Create variables to help with read and write.
            byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
            long rdlen = 0;              //This is the total number of bytes written.
            long totlen = fin.Length;    //This is the total length of the input file.
            int len;                     //This is the number of bytes to be written at a time.

            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);

            Console.WriteLine("Encrypting...");

            //Read from the input file, then encrypt and write to the output file.
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
                Console.WriteLine("{0} bytes processed", rdlen);
            }

            encStream.Close();
            fout.Close();
            fin.Close();
        }

        private static void EncryptData(MemoryStream mem, String outName, byte[] desKey, byte[] desIV)
        {
            //Create the file streams to handle the input and output files.
            //FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            //Create variables to help with read and write.
            byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
            long rdlen = 0;              //This is the total number of bytes written.
            long totlen = mem.Length;    //This is the total length of the input file.
            int len;                     //This is the number of bytes to be written at a time.

            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

            Console.WriteLine("Encrypting...");

            //Read from the input file, then encrypt and write to the output file.
            while (rdlen < totlen)
            {
                len = mem.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
                Console.WriteLine("{0} bytes processed", rdlen);
            }

            encStream.Close();
            fout.Close();
            //fin.Close();
        }

        private static void DescryptData(String inName, MemoryStream mem, byte[] desKey, byte[] desIV)
        {
            //Create the file streams to handle the input and output files.
            FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
           // FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
            //fout.SetLength(0);
            mem = new MemoryStream();
            //Create variables to help with read and write.
            byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
            long rdlen = 0;              //This is the total number of bytes written.
            long totlen = fin.Length;    //This is the total length of the input file.
            int len;                     //This is the number of bytes to be written at a time.

            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(mem, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);

            Console.WriteLine("Encrypting...");

            //Read from the input file, then encrypt and write to the output file.
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
                Console.WriteLine("{0} bytes processed", rdlen);
            }
            
            encStream.Close();
            //fout.Close();
            fin.Close();
        }
    }    
}
